# Create your views here.
# python manage.py runserver
from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import UserModel,SfLogin,UserAmount_record,RechargeModel,VipModel,VipRecordModel
from django.http import HttpResponse
import re,string,requests
import random,time,json
from random import randint

from celery_tasks.sms_code.tasks import send_message
from datetime import datetime
from utils.my_redis import r
from django.contrib.auth.hashers import check_password,make_password

# 注册
# from django.conf import settings
# settings.configure(DEBUG=True) # 声明


from captcha.image import ImageCaptcha
class Imgcode(APIView):
    def get(self,request,uuid):
        code= ''.join(random.sample(string.ascii_letters + string.digits, 4))
        cap = ImageCaptcha()
        img_code = cap.generate(code)
        r.set_str(uuid,code,120)
        return HttpResponse(img_code,content_type='image/png')




class SendSmsCode(APIView):
    def get(self,request):
        mobile = request.GET.get('mobile')
        img_code = request.GET.get('img_code')
        uuid = request.GET.get('uuid')
        if not all([mobile,img_code,uuid]):
            return Response({'code': 401, 'msg': '信息不完整'})
        r_code = r.get_str(uuid)
        if not r_code:
            return Response({'code': 401, 'msg': '图片验证码过期'})

        print(r_code)
        if img_code.lower() != r_code.decode().lower():
            return Response({'code': 401, 'msg': '图片验证码错误'})
        data = randint(100000, 999999)
        resp = send_message(mobile,data)
        print('resp>>>',resp,type(resp)) # resp:json字典
        if resp:
            # 短信发送成功后，写入redis便于后边校验
            r.set_str('sms_%s'%mobile,data,600)
            return Response({'msg':'发送成功','code':200,'data':data})
        else:
            return Response({'msg':'发送失败','code':500})


class Register(APIView):
    def post(self,request):
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        user_type = int(request.data.get('user_type'))
        code = request.data.get('code')
        new_code = r.get_str('sms_%s' % mobile)
        if not all([password,mobile,code]):
            return Response({'code': 204, 'msg': '信息不完整'})
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 204, 'msg': '手机号格式错误'})
        if UserModel.objects.filter(mobile=mobile):
            return Response({'code': 400, 'msg': '手机号重复'})
        if new_code.decode()!=code:
            return Response({"code": 400, "msg": "验证码错误"})
        s = datetime.strftime(datetime.now(), "%m%d")
        n = s + mobile[-4:]
        username='用户_'+n
        new_pwd = make_password(password)
        UserModel.objects.create(username=username,password=new_pwd,mobile=mobile,user_type=user_type)
        return Response({'code': 200, 'msg': '注册完成'})

# 登录



import jwt
from django.conf import settings

def login_jwt_token(user):
    payload={
        'userid': user.id,
        'username': user.username,
        'mobile': user.mobile,
        "exp_time": int(time.time())
    }

    token=jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
    return token




class Login(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        pwd= request.data.get('password')

        if not mobile:
            return Response({'code': 404, 'msg': '手机号为空'})
        if not re.findall(r'^\w{6,20}$', pwd):
            return Response({'code': 204, 'msg': '密码格式错误'})
        try:
            user= UserModel.objects.get(mobile=mobile)
        except Exception as e:
            print(e)
            return Response({'code': 404, 'msg': '用户不存在'})
        print(user.password)
        if not check_password(pwd, user.password):
            return Response({'code': 204, 'msg': '账号或密码错误'})
        token= login_jwt_token(user)
        return Response({
            'code': 200,
            'msg': '欢迎用户%s登录'% user.username,
            'token': token
        })

# 第三方登录

class Sina(APIView):
    def get(self,request):
        # App Key   应用ID
        client_id = "3674019597"
        # App Secret
        client_secret = "7ae99bc0d54ead29fc8d1b9fabd78587"
        # 微博回调网址
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        # 微博跳转网址
        sina_url = "https://api.weibo.com/oauth2/authorize"

        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        # 返回跳转地址
        return Response({'code': 200,'url':url})

from django.shortcuts import redirect
from utils.my_jwt import myjwt
class Sf_Loginview(APIView):
    def get(self,request):
        code = request.GET.get('code')
        # print(code)
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        mes = json.loads(res1.text)
        # print('___',mes)
        uid = mes['uid']
        token = mes['access_token']
        res=SfLogin.objects.filter(uid=uid).first()
        if res:
            user = UserModel.objects.get(id=res["userid_id"])
            jwt = {"data": {"userid": user['id'], "mobile": user["mobile"], "exptime": int(time.time())}}
            token = myjwt.jwt_encode(jwt)

            return redirect("http://127.0.0.1:8080/updatoken?token=" + token + "&userid=" + str(res['id']))
        else:
            return redirect("http://127.0.0.1:8080/weibo?token="+str(token)+"&uid="+str(uid))
    def post(self,request):
        data = json.loads(self.request.body)
        uid = data['uid']
        token = data['token']
        mobile=data['mobile']
        if not all([uid,mobile,token]):
            return Response({'code': 400, 'msg': '信息不完整'})
        user = UserModel.objects.filter(mobile=mobile).first()
        if not user:
            UserModel.objects.create(username=data['mobile'], password='123456', mobile=mobile)
        user = UserModel.objects.filter(mobile=mobile).first()
        SfLogin.objects.create(userid_id=user.id, webfrom='weibo', token=token, uid=uid,url='')
        jwt = {"data": {"userid": user.id, "mobile": mobile,"exp_time": int(time.time())}}
        token = myjwt.jwt_encode(jwt)
        return Response({'code': 200, 'msg': 'ok', 'token': token,'userid':uid})


# 充值/提现
from utils.pay import get_ali_object

class RechargePayurl(APIView):
    def get(self,request):
        # 获取支付的参数
        # data = json.loads(self.request.body)
        userid = request.GET.get('userid')
        # userid = 8
        money = float(request.GET.get('money'))
        order_name = request.GET.get('order_name')
        if money<=0:
            return Response({'code': 400, 'msg': '金额为空'})
        order_id = '010' + str(int(time.time())) + str(userid) + str(random.randint(100000, 999999))

        name='用户'+str(userid) + order_name
        RechargeModel.objects.create(money=money,order_id=order_id,userid_id=userid)

        pkey = 'order_payfail_recharge'
        r.zset_add(pkey, order_id, int(time.time()))
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject=name,  # 商品简单描述
            out_trade_no=order_id,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return Response({'code': 200, 'msg': 'ok', 'url': pay_url})



class RechargeCallback(APIView):
    def get(self,request):
        data = request.GET

        # 对参数进行处理
        data = data.dict()
        print(data)
        # 从字典中将sign删除
        sign = data.pop("sign")
        # 获取支付宝对象

        alipay = get_ali_object()
        # 调用验签
        flag = alipay.verify(data, sign)

        print(flag)
        if flag == True:
            trade_no =request.GET.get('trade_no')
            print('-_|_-',trade_no)
            out_trade_no = request.GET.get('out_trade_no')  # 订单号
            res=RechargeModel.objects.filter(order_id=out_trade_no).first()
            userid = res.userid_id
            money = res.money
            try:
                RechargeModel.objects.filter(order_id=res.order_id).update(status=1)

                users = UserModel.objects.filter(id=userid).first()
                moneys = users.money
                if moneys == 0:
                    UserModel.objects.filter(id=userid).update(money=money)
                else:
                    new_money = float(moneys) + float(money)
                    UserModel.objects.filter(id=userid).update(money=new_money)
                UserAmount_record.objects.create(type=1,status=0,user_id=userid,money=money)
                r.zset_del("order_payfail_recharge", out_trade_no)
                return redirect("http://localhost:8080/user")
            except:
                return redirect("http://localhost:8080/user")

#  vip


class Set_vipView(APIView):
    def get(self,request):
        userid = request.GET.get('userid')
        # userid = 8
        money = float(request.GET.get('money'))
        order_name = request.GET.get('order_name')
        if money<=0:
            return Response({'code': 400, 'msg': '金额为空'})
        order_id = '010' + str(int(time.time())) + str(userid) + str(random.randint(100000, 999999))
        name='用户'+str(userid) + order_name
        user=UserModel.objects.filter(id=userid).first()
        RechargeModel.objects.create(money=money, order_id=order_id, userid_id=userid)
        if user.money>=money:
            user_money=user.money
            new_money=user_money-money
            UserModel.objects.filter(id=userid).update(money=new_money)
            return Response({'code': 200, 'msg': '成功'})
        RechargeModel.objects.create(money=money,order_id=order_id,userid_id=userid)

        pkey = 'order_payfail_vip'
        r.zset_add(pkey, order_id, int(time.time()))
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject=name,  # 商品简单描述
            out_trade_no=order_id,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return Response({'code': 201, 'msg': 'ok', 'url': pay_url})



class UsersView(APIView):
    def get(self,request):
        pass












class Anlis(APIView):
    def get(self,request):
        out_trade_no = '01016788676401885054'
        money=20
        userid=1
        users = UserModel.objects.filter(id=userid).first()
        moneys = users.money
        new_money = float(moneys) + float(money)
        UserModel.objects.filter(id=userid).update(money=new_money)
        a=settings.SECRET_KEY
        print(a)
        return Response({
            'msg':a
        })











